/*
 * This class stands for the regular expression and open the template in the editor.
 */

package cz.muni.fi.xkadlec6.bp.regularExpression;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * The instance of this class stands for the regular expression
 * 
 * @author Jana Kadlecova
 */
public class RegularExpression
{

	private Node startNode;

	public RegularExpression(Node startNode)
	{
		if (startNode == null)
		{
			throw new NullPointerException("RegularExpression(): " + "a given start node is null.");
		}
		this.startNode = startNode;
	}

	public Node getStartNode()
	{
		return this.startNode;
	}

	public Set<String> getAlphabet()
	{
		Set<String> alphabet = new HashSet<String>();
		List<Node> nodes = new ArrayList<Node>();
		nodes.add(startNode);
		while (!nodes.isEmpty())
		{
			Node n = nodes.get(0);
			if (n.isOperation())
			{
				nodes.addAll(n.getChildren());
			}
			else
			{
				alphabet.add(n.getName());
			}
			nodes.remove(nodes.get(0));
		}
		alphabet.remove("epsilon");
		alphabet.remove("\\0");
		return alphabet;
	}

	public int getLength()
	{
		int length = 0;
		List<Node> nodes = new ArrayList<Node>();
		nodes.add(startNode);
		while (!nodes.isEmpty())
		{
			Node n = nodes.get(0);
			if (n.isOperation())
			{
				nodes.addAll(n.getChildren());
			}
			nodes.remove(nodes.get(0));
			length++;
		}
		return length;
	}

	@Override
	public String toString()
	{
		return this.startNode.toString();
	}

	public String toIS(String teacher, String student)
	{
		StringBuilder sb = new StringBuilder();
		sb.append(" :e\n");
		sb.append(":e=\"b:" + teacher + "-" + student + ":");
		sb.append(this.startNode.toIS());
		sb.append("\" ok\n");
		return sb.toString();
	}

	public String toLaTeX()
	{
		StringBuilder sb = new StringBuilder();
		sb.append("$$");
		sb.append(this.startNode.toLaTeX());
		sb.append("$$");
		return sb.toString();
	}

}
